#!/usr/bin/env python
# -*- coding:utf-8 -*-
from io import BytesIO
from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect
from utils.check_code import create_validate_code
import json
from utils.custom_encoder import JsonCustomEncoder

from forms.account_forms import RegisterForm
from forms.account_forms import LoginForm
from repository import models

def check_code(request):
    """
    验证码
    :param request:
    :return:
    """
    stream = BytesIO()
    img, code = create_validate_code()
    img.save(stream, 'PNG')
    request.session['checkcode'] = code
    return HttpResponse(stream.getvalue())


def login(request):
    """
    登陆
    """
    if request.method == "GET":
        return render(request, 'login.html')
    elif request.method == "POST":
        res_dict = {'status': True, 'errors': None, 'data': None}
        form_obj = LoginForm(request, request.POST)
        if form_obj.is_valid():
            res_dict['status'] = True

        else:
            print(form_obj.errors)
            res_dict['status'] = False
            res_dict['errors'] = form_obj.errors.as_data()
        if request.session.get('checkcode'):
            del request.session['checkcode']
        return HttpResponse(json.dumps(res_dict, cls=JsonCustomEncoder))






def register(request):
    """
    注册页面
    """
    if request.method == "GET":
        return render(request, 'register.html')
    elif request.method == "POST":
        res_dict = {'status': True, 'errors': None, 'data': None}
        post_data = request.POST.dict()
        form_obj = RegisterForm(request,post_data)
        if form_obj.is_valid():
            post_data.pop('password2')
            post_data.pop('checkcode')
            post_data.pop('csrfmiddlewaretoken')
            user_obj = models.UserInfo.objects.create(**post_data)
            request.session['nid'] = user_obj.nid
            request.session['is_login'] = True
            res_dict['status'] = True
        else:
            res_dict['errors'] = form_obj.errors.as_data()
            res_dict['status'] = False

        if request.session.get('checkcode'):
            del request.session['checkcode']

        return HttpResponse(json.dumps(res_dict, cls=JsonCustomEncoder))



def logout(request):
    """
    注销
    """
    request.session.clear()
    return redirect('/')

